package com.binvshe.binvshe.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.account.ui.LoginActivity;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/8/3
 * 商品选择界面
 */

public class SelectGoodsActivity extends BaseActivity {
    private static final String KEY_ACTIVITY_ID = "ACTIVITY_ID";

    @Bind(R.id.rc_date)
    RecyclerView mRcDate;
    @Bind(R.id.rc_session)
    RecyclerView mRcSession;
    @Bind(R.id.rc_price)
    RecyclerView mRcPrice;
    @Bind(R.id.tvNext)
    TextView mTvNext;
    @Bind(R.id.btnSub)
    TextView mBtnSub;
    @Bind(R.id.tvTicketNum)
    TextView mTvTicketNum;
    @Bind(R.id.btnAdd)
    TextView mBtnAdd;
    @Bind(R.id.tvTotalPrice)
    TextView mTvTotalPrice;
    @InjectExtra(KEY_ACTIVITY_ID)
    int mActivityId = -1;
    String userID;
    String gameID;

    //    private ArrayList<TicketTypeEntity> mTickMsgDatas = new ArrayList<>();
    private SelectGoodsAdapter mGoodsAdapter = new SelectGoodsAdapter(this);
    private SelectDayNightAdapter mFirnAdapter = new SelectDayNightAdapter(this);
    private TickMsgAdapter mTickMsgAdapter = new TickMsgAdapter(this);
    private int mFirID = 0;
    private int mGoodsID = 0;
    private int mTickMsgPosition = 0;
    private int mTotalNum = 1;
    private double mUnitPrice = 0.0f;
    private int mTicket_id = 0;
    TicketSelectEntity mTicketSelectEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        Dart.inject(this);
        initToolBar();
        initView();
        initData();
    }

    private void initToolBar() {
        setTitle("选择商品");
        enableBackButton();
    }

    private void initData() {
        getTickDateList();
    }

    public static void start(Context context, int activityID) {
        Intent starter = new Intent(context, SelectGoodsActivity.class);
        starter.putExtra(KEY_ACTIVITY_ID, activityID);
        context.startActivity(starter);
    }

    public void initView() {
        initRec(mRcDate, mGoodsAdapter);
        initRec(mRcSession, mFirnAdapter);
        mRcPrice.setLayoutManager(new LinearLayoutManager(this));
        mRcPrice.setAdapter(mTickMsgAdapter);
    }

    private void initRec(RecyclerView recyclerview, RecyclerViewBaseAdapter adapter) {
        recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerview.setAdapter(adapter);
    }


    @OnClick({R.id.tvNext, R.id.btnSub, R.id.btnAdd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvNext:
                // TODO: 2016/9/24 要做一个无效判断，刚进来时或者选择不全时
                createOrder();
                break;
            case R.id.btnSub:
                if (mTotalNum - 1 >= 1) {
                    mTotalNum--;
                    refreshToatleText();
                }
                break;
            case R.id.btnAdd:
                if (mTotalNum < 3) {
                    mTotalNum++;
                    refreshToatleText();
                }
                break;
        }
    }


    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_select_goods, container, false);
    }


    /**
     * 选择日期场次adapter
     */
    protected class SelectGoodsAdapter extends RecyclerViewBaseAdapter<ActivityDateEntity> {

        public SelectGoodsAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_select_goods, parent, false);
            return new VH(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            VH viewHolder = (VH) holder;
            final ActivityDateEntity data = getData().get(position);
            viewHolder.mTvContent.setText(dateText(data.getName()));
            if (!data.isSelect()) {
                viewHolder.mTvContent.setBackgroundResource(R.drawable.bg_biankuan_gray);
            } else {
                viewHolder.mTvContent.setBackgroundResource(R.drawable.bg_biankuan_blue);
            }
            setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    getTicketDayNight(getData().get(position).getActivity_id());
                    for (int i = 0; i < getData().size(); i++) {
                        if (i == position) {
                            getData().get(i).setSelect(true);
                        } else {
                            getData().get(i).setSelect(false);
                        }
                        notifyDataSetChanged();
                        mGoodsID = getData().get(position).getId();
                        refreshTicket();
                    }
                }
            });
        }

        public class VH extends RecyclerView.ViewHolder {
            @Bind(R.id.tv_content)
            TextView mTvContent;
            @Bind(R.id.rtlt_item)
            RelativeLayout mRtltItem;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /**
     * 选择日夜场次adapter
     */
    protected class SelectDayNightAdapter extends RecyclerViewBaseAdapter<ActivityTimeEntity> {


        public SelectDayNightAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_select_goods, parent, false);
            return new VH(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            VH viewHolder = (VH) holder;
            ActivityTimeEntity data = getData().get(position);
            viewHolder.mTvContent.setText(firnText(data.getName(), data.getBegin(), data.getEnd()));
            if (!data.isSelect()) {
                viewHolder.mTvContent.setBackgroundResource(R.drawable.bg_biankuan_gray);
            } else {
                viewHolder.mTvContent.setBackgroundResource(R.drawable.bg_biankuan_blue);
            }
            setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    for (int i = 0; i < getData().size(); i++) {
                        if (i == position) {
                            getData().get(i).setSelect(true);
                        } else {
                            getData().get(i).setSelect(false);
                        }
                        notifyDataSetChanged();
                        mFirID = getData().get(position).getId();
                        refreshTicket();
                    }
                }
            });
        }

        public class VH extends RecyclerView.ViewHolder {
            @Bind(R.id.tv_content)
            TextView mTvContent;
            @Bind(R.id.rtlt_item)
            RelativeLayout mRtltItem;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }


    /**
     * 获取票务信息的adapter
     */
    protected class TickMsgAdapter extends RecyclerViewBaseAdapter<TicketSelectEntity> {


        public TickMsgAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_select_ticket, parent, false);
            return new VHolder(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            VHolder viewHolder = (VHolder) holder;
            TicketSelectEntity ticketTypeEntity = getData().get(position);
            viewHolder.mTvContent.setText(getString(R.string.activity_tick_msg, ticketTypeEntity.getName(), ticketTypeEntity.getPrice() + ""));
            if (ticketTypeEntity.isSelected()) {
                viewHolder.mTvContent.setBackgroundResource(R.drawable.bg_biankuan_blue);
            } else {
                viewHolder.mTvContent.setBackgroundResource(R.drawable.bg_biankuan_gray);
            }
            setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    for (int i = 0; i < getData().size(); i++) {
                        if (i == position) {
                            getData().get(i).setSelected(true);
                        } else {
                            getData().get(i).setSelected(false);
                        }
                    }
                    mTickMsgAdapter.notifyDataSetChanged();
                    refreshPriceTotal(position);
                }
            });
        }

        public class VHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.tv_content)
            TextView mTvContent;
            @Bind(R.id.rtlt_item)
            RelativeLayout mRtltItem;

            public VHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    public String dateText(String date) {
        if (date.length() > 3) {
            String month = date.substring(0, date.length() - 3);
            String week = date.substring(date.length() - 3, date.length());
            String temp = String.format(getString(R.string.item_activity), month, week);
            return temp;
        }
        return date;
    }

    public String firnText(String firn, String begin, String end) {
        String temp = String.format(getString(R.string.item_activies_date), firn.subSequence(0, 2), firn.subSequence(2, firn.length()));
        return temp;
    }

    public void refreshTicket() {
        if (mGoodsID != -1 && mFirID != -1) {
            getTicketInfo(mActivityId, mGoodsID, mFirID);
        }
    }

    public void refreshToatleText() {
        BigDecimal total = new BigDecimal(mTotalNum);
        BigDecimal price = new BigDecimal(mUnitPrice);
        mTvTicketNum.setText(mTotalNum + "");
        String temp = getString(R.string.ticket_total_pr, total.multiply(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "");
        mTvTotalPrice.setText(Html.fromHtml(temp));
    }

    public void refreshPriceTotal(int position) {
        mTickMsgPosition = position;
        if (mTickMsgAdapter.getData().size() > 0) {
            TicketSelectEntity ticketSelectEntity = mTickMsgAdapter.getData().get(position);
            mTotalNum = 1;
            mTicket_id = ticketSelectEntity.getId();
            mUnitPrice = ticketSelectEntity.getPrice();
            gameID = ticketSelectEntity.getId() + "";
            mTicketSelectEntity = ticketSelectEntity;
        } else {
            mTicket_id = -1;
            gameID = "-1";
            mTotalNum = 0;
            mUnitPrice = 0;
        }
        refreshToatleText();
    }


    private void getTickDateList() {
        if (mActivityId != -1) {
            IHttpRequest request = new MyHttpRequest(this);
            String url = String.format(UrlCenter.TICKET_DATE, mActivityId);
            request.get(url, new UrlParams(), new DataRequestListener<List<ActivityDateEntity>>(ActivityDateEntity.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(List<ActivityDateEntity> o) {
                    if (o != null && o.size() > 0) {
                        mGoodsAdapter.getData().clear();
                        mGoodsAdapter.getData().addAll(o);
                        mGoodsAdapter.notifyDataSetChanged();
                    }
                    super.onSuccess(o);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                }
            });
        }
    }

    /**
     * 获得早晚票的接口
     *
     * @param activity_id
     */
    private void getTicketDayNight(int activity_id) {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.TICKET_SESSION, activity_id);
        request.get(url, new UrlParams(), new DataRequestListener<List<ActivityTimeEntity>>(ActivityTimeEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<ActivityTimeEntity> o) {
                mFirnAdapter.getData().clear();
                mFirnAdapter.getData().addAll(o);
                mFirnAdapter.notifyDataSetChanged();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 获得最终票务接口
     */
    private void getTicketInfo(int activityId, int cycle, int times) {
        IHttpRequest request = new MyHttpRequest(this);
        UrlParams params = new UrlParams();
        params.put(ParamKey.Activity.ACTIVITY_ID, activityId + "");
        params.put(ParamKey.Activity.CYCLE, cycle + "");
        params.put(ParamKey.Activity.TIMES, times + "");
        request.get(UrlCenter.TICKET_LIST_SELECT, params, new DataRequestListener<List<TicketSelectEntity>>(TicketSelectEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<TicketSelectEntity> o) {
                if (o != null) {
                    mTickMsgAdapter.getData().clear();
                    mTickMsgAdapter.getData().addAll(o);
                    mTickMsgAdapter.notifyDataSetChanged();
                }
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 生成订单接口
     */
    private void createOrder() {
        IHttpRequest request = new MyHttpRequest(this);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("ticket_id", mTicket_id);
            jsonObject.put("num", mTotalNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.post(UrlCenter.CREATE_ORDER, jsonObject, new DataRequestListener<OrderEntity>(OrderEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(OrderEntity o) {
                IndentSureActivity.start(SelectGoodsActivity.this, o, mTicketSelectEntity,mTotalNum);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                if(strMsg.equals("未知错误")){
                    finish();
                    EasyToast.showToast(SelectGoodsActivity.this,"请重新登录");
                    LoginActivity.start(SelectGoodsActivity.this);
                }
            }
        });
    }
}
